import { Provide } from '@midwayjs/decorator';
import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
import { Context } from 'egg';
import { Result } from '../Result';
import { CustomError } from './customError';

@Provide()
export class exceptionHandleMiddleware implements IWebMiddleware {
  resolve() {
    return async (ctx: Context, next: IMidwayWebNext) => {
      try {
        await next();
      } catch (error) {
        if (error instanceof CustomError) {
          ctx.body = Result.error(error.code, error.message);
        } else {
          console.log(`访问接口：${ctx.url} 报错，错误信息：`);
          console.log(error);
          ctx.body = Result.error(500, error.message);
        }
      }
    };
  }
}
